import { access, rm, mkdir } from 'fs/promises';
import { ReadStream } from 'typeorm/platform/PlatformTools';
import { writeFile } from 'fs/promises';
import { dirname } from 'path';

export async function fsExist(file: string) {
  try {
    await access(file);
    return true;
  } catch (e) {
    return false;
  }
}

export async function clearDir(dirname: string) {
  try {
    const ifFileExist = await fsExist(dirname);
    if (ifFileExist) {
      await rm(dirname, { recursive: true });
    }
    await mkdir(dirname);
  } catch (e) {
    console.log('清除文件夹失败');
  }
}

export async function getReadStreamLength(
  readStream: ReadStream,
): Promise<number> {
  return new Promise((resolve, reject) => {
    let length = 0;
    readStream.on('data', function (chunk) {
      length += chunk.length;
    });
    readStream.on('end', () => {
      resolve(length);
    });

    readStream.on('error', function (err) {
      reject(err);
    });
  });
}

export async function safeWriteFile(
  filename: string,
  data: Parameters<typeof writeFile>[1],
) {
  try {
    return await writeFile(filename, data);
  } catch (error: any) {
    // 如果是文件夹不存在
    if (error.errno === -2 && error.syscall === 'open') {
      await mkdir(dirname(filename), { recursive: true });
      return safeWriteFile(filename, data);
    }
    throw error;
  }
}
